package cn.tedu.knows.portal.controller;


import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.model.Answer;
import cn.tedu.knows.portal.service.IAnswerService;
import cn.tedu.knows.portal.vo.AnswerVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2021-11-26
 */
@RestController
@RequestMapping("/v1/answers")
@Slf4j
public class AnswerController {
    @Autowired
    private IAnswerService answerService;
//新增回复的路径就是/v1/answers
    @PostMapping("")
    //添加回答必须有相应的权限
//    @PreAuthorize("hasAuthority('/question/answer')")
    //也可以使用下面验证角色(身份)的写法
    @PreAuthorize("hasRole('ROLE_TEACHER')")
    //hasRole是专门验证角色(身份)的指令
    // Spring-Security识别以ROLE_开头的资格为角色
    // 在使用hasRole验证时,可以省略ROLE_的编写,简化角色判断

    public Answer postAnswer(
            @Validated AnswerVO answerVO,
            BindingResult result,
            @AuthenticationPrincipal UserDetails user){
        log.debug("表单信息:{}",answerVO);
        if (result.hasErrors()){
            String msg=result.getFieldError().getDefaultMessage();
            //
            throw new ServiceException(msg);
        }
        // 这里调用业务逻辑层方法
        // ↓↓↓↓↓↓↓↓↓↓↓  接收业务逻辑层中新增成功返回的Answer对象
        Answer answer=answerService.saveAnswer(answerVO,user.getUsername());
        return answer;
    }
    //   /v1/answers/question/149
    @GetMapping("/question/{id}")
    public List<Answer> questionAnswers(
            @PathVariable Integer id) {
        List<Answer> answers = answerService.getAnswersByQuestionId(id);
        return answers;
    }
}
